// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/functions/prestosql/aggregates/bool_aggregates.h>
#include <pollux/exec/aggregate.h>
#include <pollux/expression/function_signature.h>
#include <pollux/functions/lib/aggregates/simple_numeric_aggregate.h>
#include <pollux/functions/prestosql/aggregates/aggregate_names.h>

using namespace kumo::pollux::functions::aggregate;

namespace kumo::pollux::aggregate::prestosql {
    namespace {
        class BoolAndOrAggregate : public SimpleNumericAggregate<bool, bool, bool> {
        protected:
            using BaseAggregate = SimpleNumericAggregate<bool, bool, bool>;

        public:
            explicit BoolAndOrAggregate(bool initialValue)
                : BaseAggregate(BOOLEAN()), initialValue_(initialValue) {
            }

            int32_t accumulatorFixedWidthSize() const override {
                return sizeof(bool);
            }

            void extractValues(char **groups, int32_t numGroups, VectorPtr *result)
            override {
                auto *vector = (*result)->as<FlatVector<bool> >();
                POLLUX_CHECK(vector);
                vector->resize(numGroups);

                uint64_t *rawNulls = getRawNulls(vector);
                uint64_t *rawValues = vector->mutableRawValues<uint64_t>();

                for (int32_t i = 0; i < numGroups; ++i) {
                    char *group = groups[i];
                    if (isNull(group)) {
                        vector->set_null(i, true);
                    } else {
                        clearNull(rawNulls, i);
                        bits::setBit(rawValues, i, *value<bool>(group));
                    }
                }
            }

            void extractAccumulators(char **groups, int32_t numGroups, VectorPtr *result)
            override {
                extractValues(groups, numGroups, result);
            }

        protected:
            void initializeNewGroupsInternal(
                char **groups,
                melon::Range<const vector_size_t *> indices) override {
                setAllNulls(groups, indices);
                for (auto i: indices) {
                    *value<bool>(groups[i]) = initialValue_;
                }
            }

            const bool initialValue_;
        };

        class BoolAndAggregate final : public BoolAndOrAggregate {
        public:
            explicit BoolAndAggregate() : BoolAndOrAggregate(/* initialValue = */ true) {
            }

            void addRawInput(
                char **groups,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool mayPushdown) override {
                BaseAggregate::updateGroups<true>(
                    groups,
                    rows,
                    args[0],
                    [](bool &result, bool value) { result = result && value; },
                    mayPushdown);
            }

            void addIntermediateResults(
                char **groups,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool mayPushdown) override {
                return addRawInput(groups, rows, args, mayPushdown);
            }

            void addSingleGroupRawInput(
                char *group,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool mayPushdown) override {
                BaseAggregate::updateOneGroup(
                    group,
                    rows,
                    args[0],
                    [](bool &result, bool value) { result = result && value; },
                    [](bool &result, bool value, int /* unused */) {
                        result = result && value;
                    },
                    mayPushdown,
                    this->initialValue_);
            }

            void addSingleGroupIntermediateResults(
                char *group,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool mayPushdown) override {
                addSingleGroupRawInput(group, rows, args, mayPushdown);
            }
        };

        class BoolOrAggregate final : public BoolAndOrAggregate {
        public:
            explicit BoolOrAggregate() : BoolAndOrAggregate(/* initialValue = */ false) {
            }

            void addRawInput(
                char **groups,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool mayPushdown) override {
                BaseAggregate::updateGroups<true>(
                    groups,
                    rows,
                    args[0],
                    [](bool &result, bool value) { result = result || value; },
                    mayPushdown);
            }

            void addIntermediateResults(
                char **groups,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool mayPushdown) override {
                addRawInput(groups, rows, args, mayPushdown);
            }

            void addSingleGroupRawInput(
                char *group,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool mayPushdown) override {
                BaseAggregate::updateOneGroup(
                    group,
                    rows,
                    args[0],
                    [](bool &result, bool value) { result = result || value; },
                    [](bool &result, bool value, int /* unused */) {
                        result = result || value;
                    },
                    mayPushdown,
                    this->initialValue_);
            }

            void addSingleGroupIntermediateResults(
                char *group,
                const SelectivityVector &rows,
                const std::vector<VectorPtr> &args,
                bool mayPushdown) override {
                addSingleGroupRawInput(group, rows, args, mayPushdown);
            }
        };

        template<class T>
        exec::AggregateRegistrationResult registerBool(
            const std::string &name,
            bool withCompanionFunctions,
            bool overwrite) {
            // TODO Fix signature to match Presto.
            std::vector<std::shared_ptr<exec::AggregateFunctionSignature> > signatures = {
                exec::AggregateFunctionSignatureBuilder()
                .returnType("boolean")
                .intermediateType("boolean")
                .argumentType("boolean")
                .build()
            };

            return exec::registerAggregateFunction(
                name,
                std::move(signatures),
                [name](
            core::AggregationNode::Step step,
            const std::vector<TypePtr> &argTypes,
            const TypePtr & /*resultType*/,
            const core::QueryConfig & /*config*/)
            -> std::unique_ptr<exec::Aggregate> {
                    POLLUX_CHECK_EQ(argTypes.size(), 1, "{} takes only one argument", name);
                    auto inputType = argTypes[0];
                    POLLUX_CHECK_EQ(
                        inputType->kind(),
                        TypeKind::BOOLEAN,
                        "Unknown input type for {} aggregation {}",
                        name,
                        inputType->kindName());
                    return std::make_unique<T>();
                },
                {false /*orderSensitive*/, false /*companionFunction*/},
                withCompanionFunctions,
                overwrite);
        }
    } // namespace

    void registerBoolAggregates(
        const std::string &prefix,
        bool withCompanionFunctions,
        bool overwrite) {
        registerBool<BoolAndAggregate>(
            prefix + kBoolAnd, withCompanionFunctions, overwrite);
        registerBool<BoolAndAggregate>(
            prefix + kEvery, withCompanionFunctions, overwrite);
        registerBool<BoolOrAggregate>(
            prefix + kBoolOr, withCompanionFunctions, overwrite);
    }
} // namespace kumo::pollux::aggregate::prestosql
